package com.bpmn.filter;

import cn.hutool.core.util.StrUtil;
import com.bpmn.common.constant.CommonConstants;
import com.bpmn.common.holder.TenantContextHolder;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 多租户 Context Web 过滤器
 * 将请求 Header 中的 tenant-id 解析出来，添加到 {@link TenantContextHolder} 中，这样后续的 DB 等操作，可以获得到租户编号。
 *
 * @author rain
 */
@Slf4j
@Component
public class TenantContextWebFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain chain) throws IOException, ServletException {
        String headerTenantId = request.getHeader(CommonConstants.TENANT_ID);
        String paramTenantId = request.getParameter(CommonConstants.TENANT_ID);
        log.debug("获取header中的租户ID为:{}", headerTenantId);
        if (StrUtil.isNotBlank(headerTenantId)) {
            TenantContextHolder.setTenantId(headerTenantId);
        } else if (StrUtil.isNotBlank(paramTenantId)) {
            TenantContextHolder.setTenantId(paramTenantId);
        } else {
            TenantContextHolder.setTenantId(CommonConstants.TENANT_ID_DEFAULT);
        }
        try {
            chain.doFilter(request, response);
        } finally {
            TenantContextHolder.clear();
        }
    }

}
